package fr.gdi.android.news.api;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public abstract class BasicWebBrowsingActivity extends Activity
{
    private WebView browser;
    
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.browse);
        
        browser = (WebView) findViewById(R.id.browser);
        
        configureBrowser();

        onNewIntent(getIntent());
        
    }
    
    @Override
    protected void onNewIntent(Intent intent)
    {
        String url = intent.getDataString();
        browser.loadUrl(url);
    }

    private void configureBrowser()
    {
        browser.getSettings().setAppCacheEnabled(true);
        browser.getSettings().setLightTouchEnabled(true);
        browser.getSettings().setSupportZoom(true);
        browser.getSettings().setJavaScriptEnabled(true);
        browser.setVerticalScrollBarEnabled(false);
        
        final Activity context = this;
        
        browser.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
                context.setProgress(progress * 100);
            }
        });
        
        browser.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                Uri uri = Uri.parse(url);
                if ( uri.getScheme().equals(getUrlScheme()) )
                {
                    Intent intent = new Intent().setData(uri).setAction(Intent.ACTION_VIEW).addCategory(Intent.CATEGORY_BROWSABLE);
                    //intent.putExtras(getIntent());
                    startActivity(intent);
                    //moveTaskToBack(true);
                    finish();
                }
                else 
                {
                    view.loadUrl(url);
                }
                return true;
            } 
        });
    }
    
    protected abstract String getUrlScheme();
}
